import {Divider, Popconfirm, Input, Select, message} from 'antd'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import {connect} from 'umi'
import {addSecurityUser, deleteEmployeeSecurity, getItemBySecurityId} from '../../service'
import {employeeStatusList} from "@/utils/constant";

const {Option} = Select

const TableForm = ({addUserList, securityInfo, securityUserItems, tableToolbarRender}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [fixedAmountData, setFixedAmountData] = useState({});
  const [data, setData] = useState([]);
  const [showFlag,setShowFlag] = useState({
    showReservedFunds : true,
    showOfferFunds : true
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      disabled: true,
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      disabled: true
    },
    {
      title: '公司',
      dataIndex: 'orgname',
      key: 'orgname',
      disabled: true
    },
    {
      title: '状态',
      dataIndex: 'employeestatus',
      key: 'employeestatus',
      disabled: true,
      render: (text,record) =>{
        return text!=='-' ? employeeStatusList.find(item => (item.value===text)).label : ''
      }
    },
    {
      title: '公积金基数',
      dataIndex: 'reservedFunds',
      key: 'reservedFunds',
      hideInTable: showFlag.showPension,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.reservedFunds} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'reservedFunds', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '补充公积金基数',
      dataIndex: 'offerFunds',
      key: 'offerFunds',
      hideInTable: showFlag.showOfferFunds,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.offerFunds} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'offerFunds', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '150px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="删除此行会产生异动记录，是否删除？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ];

  useEffect(() => {
    setLoading(true);
    getItemBySecurityId(securityInfo.typeId).then(res =>{
      let flag = {...showFlag};
      if (res){
        let fixedAmountObj = {};
        res.forEach((item,index) =>{
          if (item.securityType === 5){
            flag.showReservedFunds = false;
            fixedAmountObj.reservedFunds = item.personalFixedAmount;
          }else if (item.securityType === 6){
            flag.showOfferFunds = false;
            fixedAmountObj.offerFunds = item.personalFixedAmount;
          }
        });
        setFixedAmountData(fixedAmountObj);
        setShowFlag(flag);
      }
    });
    if (securityUserItems.length > 0){
      setData(securityUserItems.map((item,index) =>{
        return {key: 'had'+index, ...item, ...securityInfo};
      }))
    }
    if (addUserList.length > 0) {
      let newData = [...data];
      for (let i = 0; i < addUserList.length; i++) {
        let isContinue = false;
        for (let a = 0; a < data.length; a++) {
          if (data[a].oid === addUserList[i].oid)
            isContinue = true;
        }
        if (isContinue)
          continue;
        newData.push({
          key: addUserList[i].oid,
          id: null,
          oid: addUserList[i].oid,
          name: addUserList[i].name,
          orgname: addUserList[i].orgname,
          ...securityInfo,
          code: addUserList[i].code,
          employeestatus: addUserList[i].employeestatus,
          ...fixedAmountData
        });
      }
      setData(newData);
    }
    setLoading(false);
  }, [addUserList,securityUserItems]);

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key, record) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      if (record){
        target.id = record.id;
        target.reservedFunds = record.reservedFunds;
        target.offerFunds = record.offerFunds;
      }
      setData(newData)
    }
  };

  const remove = (e, record) => {
    setLoading(true);
    const newData = [...data];
    if (record.id){
      deleteEmployeeSecurity(record.id, securityInfo.typeId, securityInfo.type,  record.oid).then(res => {
        if (res.flag){
          message.success('公积金方案人员删除成功！');
          let datas = newData.filter(item => item.key !== record.key);
          setData(datas)
        }else {
          message.error(res.error);
        }
        setLoading(false);
      });
    }else {
      let datas = newData.filter(item => item.key !== record.key);
      setData(datas);
      setLoading(false);
    }
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData)
    }
  };


  const updateRow = (e, rowKey, oid) => {
    setLoading(true);
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    const target = getRowByKey(rowKey) || {}
    addSecurityUser(target).then(res =>{
      if (res.flag){
        toggleEditable(e, rowKey, res.data);
        message.success('公积金方案人员绑定成功！');
      }else {
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据

    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...item, ...cacheOriginData[key], editable: false}
          delete cacheOriginData[key]
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    setData(cacheData);
    setClickedCancel(false)
  };

  return (
    <>
      <ProTable
        headerTitle='人员配置列表'
        loading={loading}
        columns={columns}
        dataSource={data}
        search={false}
        toolBarRender={tableToolbarRender}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />
    </>
  )
};

export default connect(({  }) => ({

}))(TableForm)

